﻿/*****************************************介绍*****************************************
 * 作者：Ywh
 * 创建时间：2024-03-05　10:30:00
 * 功能：自动生成的数据后处理
**************************************************************************************/

using LitJson;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

public class AutoDataPostprocess : AssetPostprocessor
{
    private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        for (int i = 0; i < importedAssets.Length; i++)
        {
            // 处理资源
            string name = Path.GetFileName(importedAssets[i]);
            switch (name)
            {
                case "AbilityStageTip.json":
                    string finalPath = $"Assets/HotFixResources/Configs/Ability/{name}";
                    if (importedAssets[i].Equals(finalPath)) break;
                    AssetDatabase.DeleteAsset(finalPath);
                    AssetDatabase.MoveAsset(importedAssets[i], finalPath);
                    break;
                case "CharacterPropNames.json":
                case "PlayerOnlyPropNames.json":
                    GenerateNewScript(importedAssets[i]);
                    break;
            }
        }
    }

    private static void GenerateNewScript(string path)
    {
        string fileName = Path.GetFileNameWithoutExtension(path);
        string finalPath = $"Assets/Modules/GlobalModule/PropertyConst/{fileName}.cs";

        if (m_HasFieldDict == null)
            m_HasFieldDict = new Dictionary<string, string>();
        m_HasFieldDict.Clear();
        TextAsset asset = AssetDatabase.LoadAssetAtPath<TextAsset>(path);
        StringBuilder sb = GenHead(asset.name);
        GenBody(asset, sb);
        GenEnd(sb);
        SaveFile(sb.ToString(), finalPath);
        AssetDatabase.DeleteAsset(path);
    }

    #region 生成脚本

    private static Dictionary<string, string> m_HasFieldDict;

    private static string GetFiledName(Regex regexNum, Regex regexSpecificSymbol, string propName)
    {
        string filedName = "";
        string[] subs = regexSpecificSymbol.Split(propName);
        foreach (string s in subs)
        {
            filedName += $"{s.Substring(0, 1).ToUpper()}{s.Substring(1)}";
        }

        if (regexNum.IsMatch(filedName))
        {
            filedName = $"_{filedName}";
        }
        if (m_HasFieldDict.ContainsKey(filedName))
            filedName = $"_{filedName}";
        m_HasFieldDict.Add(filedName, propName);
        return filedName;
    }

    private static StringBuilder GenHead(string fileName)
    {
        StringBuilder sb = new StringBuilder();
        string funcDesc = GetFuncDesc(fileName);
        sb.AppendLine("/*****************************************介绍*****************************************");
        sb.AppendLine($" * 作者：{Environment.UserName}");
        sb.AppendLine($" * 创建时间：{DateTime.Now.ToString("yyyy-MM-dd\u3000hh:mm:ss")}");
        sb.AppendLine($" * 功能：{funcDesc}");
        sb.AppendLine("**************************************************************************************/");
        sb.AppendLine();
        sb.AppendLine("using Atavism;");
        sb.AppendLine("using UnityEngine;");
        sb.AppendLine();
        sb.AppendLine($"public class {fileName}");
        sb.AppendLine("{");
        return sb;
    }

    private static string GetFuncDesc(string fileName)
    {
        string funcDesc = "";
        switch (fileName)
        {
            case "PlayerOnlyPropNames":
                funcDesc = "玩家独有的属性名称常量类";
                break;
            case "CharacterPropNames":
                funcDesc = "角色共有的属性名称常量类";
                break;
        }

        return funcDesc;
    }

    private static void GenBody(TextAsset asset, StringBuilder sb)
    {
        JsonData data = JsonMapper.ToObject(asset.text);
        Regex regexNum = new Regex(@"^\d+.*");
        Regex regexSpecificSymbol = new Regex(@"\.|_");
        int index = 0;
        foreach (JsonData jsonData in data)
        {
            string summary = jsonData["summary"].ToString();
            string propName = jsonData["propName"].ToString();
            string type = jsonData["type"].ToString();
            string filedName = GetFiledName(regexNum, regexSpecificSymbol, propName);
            sb.AppendLine("\t/// <summary>");
            if (!string.IsNullOrEmpty(summary))
                sb.AppendLine($"\t/// {summary}");
            sb.AppendLine("\t" + @$"/// <para>数据类型：<see cref=""{type}""/></para>");
            sb.AppendLine("\t/// </summary>");
            sb.AppendLine("\t" + @$"public const string {filedName} = ""{propName}"";");
            index++;
            if (index < data.Count)
                sb.AppendLine();
        }
    }

    private static void GenEnd(StringBuilder sb)
    {
        sb.Append("}");
    }

    private static void SaveFile(string fileContent, string savePath)
    {
        File.WriteAllText(savePath, fileContent);
        AssetDatabase.Refresh();
        //Debug.Log($"生成：【{savePath}】完成 -- 共【{m_HasFieldDict.Count}】个字段！！");
        m_HasFieldDict.Clear();
        m_HasFieldDict = null;
    }

    #endregion
}